"""
日志系统
提供统一的日志记录功能
"""

import logging
import sys
from pathlib import Path
from logging.handlers import RotatingFileHandler
from typing import Optional


class Logger:
    """日志管理器"""

    def __init__(
        self,
        name: str = "AIVtuber",
        level: str = "INFO",
        log_to_file: bool = True,
        log_file: str = "./logs/ai_vtuber.log",
        max_file_size: int = 10485760,  # 10MB
        backup_count: int = 5
    ):
        """
        初始化日志管理器
        
        Args:
            name: 日志记录器名称
            level: 日志级别
            log_to_file: 是否输出到文件
            log_file: 日志文件路径
            max_file_size: 单个日志文件最大大小(字节)
            backup_count: 保留的日志文件数量
        """
        self.logger = logging.getLogger(name)
        self.logger.setLevel(getattr(logging, level.upper()))

        # 避免重复添加处理器
        if self.logger.handlers:
            return

        # 日志格式
        formatter = logging.Formatter(
            fmt='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

        # 控制台处理器
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        self.logger.addHandler(console_handler)

        # 文件处理器
        if log_to_file:
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)

            file_handler = RotatingFileHandler(
                log_file,
                maxBytes=max_file_size,
                backupCount=backup_count,
                encoding='utf-8'
            )
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(formatter)
            self.logger.addHandler(file_handler)

    def debug(self, message: str):
        """记录DEBUG级别日志"""
        self.logger.debug(message)

    def info(self, message: str):
        """记录INFO级别日志"""
        self.logger.info(message)

    def warning(self, message: str):
        """记录WARNING级别日志"""
        self.logger.warning(message)

    def error(self, message: str):
        """记录ERROR级别日志"""
        self.logger.error(message)

    def critical(self, message: str):
        """记录CRITICAL级别日志"""
        self.logger.critical(message)

    def exception(self, message: str):
        """记录异常信息(包含堆栈跟踪)"""
        self.logger.exception(message)


# 创建全局日志实例
_logger_instance: Optional[Logger] = None


def get_logger(
    name: str = "AIVtuber",
    level: str = "INFO",
    log_to_file: bool = True,
    log_file: str = "./logs/ai_vtuber.log",
    max_file_size: int = 10485760,
    backup_count: int = 5
) -> Logger:
    """
    获取日志管理器单例
    
    Args:
        name: 日志记录器名称
        level: 日志级别
        log_to_file: 是否输出到文件
        log_file: 日志文件路径
        max_file_size: 单个日志文件最大大小
        backup_count: 保留的日志文件数量
        
    Returns:
        Logger实例
    """
    global _logger_instance
    if _logger_instance is None:
        _logger_instance = Logger(
            name=name,
            level=level,
            log_to_file=log_to_file,
            log_file=log_file,
            max_file_size=max_file_size,
            backup_count=backup_count
        )
    return _logger_instance
